import AITalk from './talkTemplate';
import { replaceHtmlFragment } from '@/views/bpmn/utility/utility';
import AIWorkflow from './workFlow';
import _ from 'lodash';
/** 分割文件名 */
export const splitName = (string, start = 2, end = -1) => {
	if (!string) {
		return '';
	}
	console.log(string.length);
	if (string.length <= 14) {
		return string;
	}
	if (string.includes('.')) {
		const [name, suffix] = string.split('.');
		console.log(name, suffix);
		if (name.length > 3) {
			const ago = name.slice(0, start);
			const later = name.slice(end);
			const res = `${ago}...${later}.${suffix}`;
			console.log(ago, later, res);
			return res;
		}
		const res = `${name}.${suffix}`;
		return res;
	}
	const name = string;
	console.log(name);
	if (name.length > 3) {
		const ago = name.slice(0, start);
		const later = name.slice(end);
		const res = `${ago}...${later}`;
		return res;
	}
	const res = `${name}`;
	return res;
};

/** 获取节点名称 */
export const getNodeTitle = (taskId, completed = true) => {
	if (!taskId || taskId.length <= 0) {
		return '';
	}
	const parts = taskId.split('_');
	if (parts.length <= 0) {
		return '';
	}

	const workflowName = AITalk.WorkflowNodeName[parts[0]];
	// console.log('taskId::', taskId);
	if (parts[0] === 'BlankNode') {
		return `${workflowName} ${parts[1]}`;
	}
	if (completed) {
		// return `流程${parts[1]} ${workflowName}`
		return `${workflowName} ${parts[1]}`;
	}
	return `${workflowName} ${parts[1]} (未编辑)`;
};

// 筛选全部的下一步
const flattenObject = (node, jumpTo) => {
	let keys = Object.keys(node);
	for (let i = 0; i < keys.length; i++) {
		if (typeof node[keys[i]] !== 'object' || !node[keys[i]]) {
			continue;
		} else if (node[keys[i]] === 'jump-to') {
			jumpTo.push(node);
		} else {
			flattenObject(node[keys[i]], jumpTo);
		}
	}
};

// get all  parent  nodes of a spacial node
export const getAllParentNodes = (worksteps, node) => {
	const findRoot = (childrenNode, nodeName, parents) => {
		let keys = Object.keys(childrenNode);
		for (let i = 0; i < keys.length; i++) {
			for (let j = 0; j < childrenNode[keys[i]].length; j++) {
				if (childrenNode[keys[i]][j].id === nodeName && !childrenNode[keys[i]][j].processed) {
					// console.log('findRoot : ', item);
					parents.push(keys[i]);
					childrenNode[keys[i]][j].processed = true;
					findRoot(childrenNode, keys[i], parents);
					break;
				}
			}
		}
	};

	let flatten = {};
	let talks = Object.keys(worksteps);
	for (let i = 0; i < talks.length; i++) {
		let jumpTo = [];
		console.log(worksteps[talks[i]]);
		flattenObject(worksteps[talks[i]], jumpTo);
		if (jumpTo.length > 0) {
			flatten[talks[i]] = jumpTo;
		}
	}
	flatten = _.cloneDeep(flatten);
	let parents = [];
	findRoot(flatten, node, parents);
	console.log(parents, 'parents');
	return parents;
};

/** 获取所有节点的名称 */
export const getAllWorkstepName = (worksteps, curTaskId = '') => {
	let steps = [{ taskName: '新的流程节点', taskId: 'BlankNode' }];
	let keys = Object.keys(worksteps);
	for (let i = 0; i < keys.length; i++) {
		let node = worksteps[keys[i]];
		if (typeof node !== 'object') {
			continue;
		}
		if (node.id !== curTaskId) {
			// get task name from task id
			const taskName = getNodeTitle(node.id, node.completed);
			steps.push({ taskId: node.id, taskName: taskName, completed: node.completed });
		}
	}
	return steps;
};

export const changeNextSteps = steps => {
	console.log('SET_UPDATED_NEXT_STEPS : ', steps);
	const stepNodes = steps.steps;
	stepNodes.forEach(item => {
		if (item.previous) {
			if (item.current) {
				let data = state.worksteps;
				verifyAllCompletion(data, '', 'VERIFY_MESSAGE_SUMMARY');
				state.worksteps = { ...data };
			}
		}
	});
};

// 下载肯定回答 NLU  negative positive
export const downloadNluKeys = (libType, point) => {
	window.open(`${loginUrl}/ivcs/znlu/api/v1/intent_libs/${libType}/intents_for_testlangfile/${point}`);
};

export const validateWaitTime = (rule, value, callback) => {
	if (Number(value) < AITalk.aiWorkflowRules.waitTime.min) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.waitTime.min} 与 ${AITalk.aiWorkflowRules.waitTime.max} 之间`));
		return;
	}
	if (Number(value) > AITalk.aiWorkflowRules.waitTime.max) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.waitTime.min} 与 ${AITalk.aiWorkflowRules.waitTime.max} 之间`));
		return;
	}
	callback();
};
export const validateTimesMax = (rule, value, callback) => {
	if (Number(value) < AITalk.aiWorkflowRules.maxTalkTimes.min) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.maxTalkTimes.min} 与 ${AITalk.aiWorkflowRules.maxTalkTimes.max} 之间`));
		return;
	}
	if (Number(value) > AITalk.aiWorkflowRules.maxTalkTimes.max) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.maxTalkTimes.min} 与 ${AITalk.aiWorkflowRules.maxTalkTimes.max} 之间`));
		return;
	}
	callback();
};

export const stringlength = str => {
	let len = 0;
	for (let i = 0; i < str.length; i++) {
		let c = str.charCodeAt(i);
		//单字节加1
		if (c >= 0x0001 && c <= 0x007e || c >= 0xff60 && c <= 0xff9f) {
			len++;
		} else {
			len += 2;
		}
	}
	console.log('字符长度：', len);
	return len;
};
export const validateWords = (rule, value, callback) => {
	// console.log(value.length);
	let chineseAndEnglish = new RegExp('^[A-Za-z\u4e00-\u9fa5，。！？,.!?]+$', 'g').test(value);
	if (chineseAndEnglish) {
		if (stringlength(value.trim()) > 1000 || stringlength(value.trim()) < 1) {
			callback(new Error('可输入中文字符1~500字；英文及符号1-1000字符'));
			return;
		}
	}
	callback();
	return;
};

export const validateConfidence = (rule, value, callback) => {
	if (Number(value) < AITalk.aiWorkflowRules.confidence.min) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.confidence.min} 与 ${AITalk.aiWorkflowRules.confidence.max} 之间`));
		return;
	}
	if (Number(value) > AITalk.aiWorkflowRules.confidence.max) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.confidence.min} 与 ${AITalk.aiWorkflowRules.confidence.max} 之间`));
		return;
	}
	callback();
};

export const validateResultDataType = (rule, value, callback) => {
	if (AIWorkflow.cloneForm.associatedVariable.type === value || AIWorkflow.cloneForm.associatedVariable.type === '') {
		callback();
		return;
	} else if (AIWorkflow.cloneForm.associatedVariable && AIWorkflow.cloneForm.typeOfCollectedResults !== AIWorkflow.cloneForm.associatedVariable.type) {
		console.warn('AIWorkflow.cloneForm.typeOfCollectedResults', AIWorkflow.cloneForm.typeOfCollectedResults);
		console.log('associatedVariable', AIWorkflow.cloneForm.associatedVariable.type);
		// numericString text numeric
		if (['numericString', 'text'].includes(AIWorkflow.cloneForm.typeOfCollectedResults) && AIWorkflow.cloneForm.associatedVariable.type === 'text') {
			callback();
			return
		}
		callback(new Error('关联变量数据类型与当前模块收集结果数据类型不一致，请重新编辑'));
		return;
	}
	callback();
};

export const vaildateRepeats = (rule, value, callback) => {
	let arr = AIWorkflow.cloneForm.form.intention.filter(item => item.answerIntention === value);
	if (arr.length > 1) {
		return callback(new Error('该回答分支已被使用，请输入别的回答分支'));
	}
	return callback();
};

export const vaildateanswerIntentionSelect = (rule, value, callback) => {
	let arr = this.form.intention.filter(item => item.answerIntentionSelect === value);
	if (arr.length > 1) {
		return callback(new Error('该回答分支已被使用，请选择别的回答分支'));
	}
	return callback();
};

// Ai说 非必填 校验中文字符1~500字；英文1-1000个
export const validateAispeck = (rule, value, callback) => {
	let chineseAndEnglish = new RegExp('^[A-Za-z\u4e00-\u9fa5，。！？,.!?]+$', 'g').test(value);
	if (!value) {
		callback();
		return;
	}
	if (chineseAndEnglish) {
		if (stringlength(value.trim()) > 1000 || stringlength(value.trim()) < 1) {
			callback(new Error('可输入中文字符1~500字；英文及符号1-1000字符'));
			return;
		}
	}
	callback();
	return;
};

// validateInformationPushUrl
export const validateInformationPushUrl = (rule, value, callback) => {
	// console.log(value, rule, 'validateInformationPushUrl');
	// let flag = new RegExp(/(http|https):\/\/\S*/).test(value);
	if (!value) {
		return callback();
	}
	if (value.startsWith('http://') || value.startsWith('https://')) {
		return callback();
	} else {
		return callback(new Error('所输入的URL地址需为https://或http://开头'));
	}
};


export const validateInformationRushurlAddress = (rule, value, callback) => {
	// console.log(value, rule, 'validateInformationRushurlAddress');
	// let flag = new RegExp(/(http|https):\/\/\S*/).test(value);
	if (!value) {
		return callback(new Error('请输入URL地址'));
	}
	// else if (!flag) {
	// 	return callback(new Error('所输入的URL地址需为https://或http://开头'));
	// }
	if (value.startsWith('http://') || value.startsWith('https://')) {
		return callback();
	} else {
		return callback(new Error('所输入的URL地址需为https://或http://开头'));
	}
	// return callback();
};

export const validateWordage = (rule, value, callback) => {
	let flag = new RegExp('^[A-Za-z0-9\u4e00-\u9fa5]+$', 'g').test(value);
	if (!flag && value.trim() === '') {
		return callback(new Error('请输入文本内容'));
	} else if (replaceHtmlFragment(value).length < 1 || value.length >= 1501) {
		console.log('validateWordage', value);
		return callback(new Error('仅支持输入1500个中文汉字'));
	}
	console.log(replaceHtmlFragment(value).length);
	return callback();
};
// 验证上传video https 地址
export const validateVideoLink = (rule, value, callback) => {
	// console.log(rule, value);
	if (AIWorkflow.cloneForm.wordsSendContents.fileList.length > 0 && value && value.length !== 0) {
		callback('您已上传视频，无需填写视频地址！');
		return;
	} else if (AIWorkflow.cloneForm.wordsSendContents.fileList.length === 0 && !value.startsWith('https://')) {
		// console.log(value);
		return callback('链接当前仅支持 https！');
	}
	callback();
};
export const validateLink = (rule, value, callback) => {
	if (!value.startsWith('https://')) {
		return callback('链接当前仅支持 https！');
	}
	return callback();
};

export const validateShortVideoCollectTime = (rule, value, callback) => {
	if (Number(value) < AITalk.aiWorkflowRules.shortVideoTime.min) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.shortVideoTime.min} 与 ${AITalk.aiWorkflowRules.shortVideoTime.max} 之间`));
		return;
	}
	if (Number(value) > AITalk.aiWorkflowRules.shortVideoTime.max) {
		callback(new Error(`数值在 ${AITalk.aiWorkflowRules.shortVideoTime.min} 与 ${AITalk.aiWorkflowRules.shortVideoTime.max} 之间`));
		return;
	}
	callback();
};
export const validateRequestApiWaitTime = (rule, value, callback) => {
	// console.log(value, 'validateRequestApiWaitTime');
	if (!value) {
		return callback(new Error('请输入调取接口的等待时长'));
	} else if (value < 1000) {
		return callback(new Error('最小等待时长1000ms'));
	}
	callback();
};
